package com.sunwhite.jdbc.MyJdbc.advise;

import com.sunwhite.jdbc.MyJdbc.MyJdbcTemplate;
import com.sunwhite.jdbc.MyJdbc.interfaces.MyJdbc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionAdvise implements InvocationHandler {

  private Object obj;
  // 构造方法传入被代理的对象
  public ConnectionAdvise(Object obj) {
    this.obj = obj;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 创建Sql连接
    createConnection();
    Object value = method.invoke(obj, args);
    closeConnection();
    // 关闭sql连接
    return value;
  }

  private void createConnection() {
    try {
      System.out.println("Connection连接");
      Class.forName("com.mysql.jdbc.Driver");
      Connection connection =
          DriverManager.getConnection(MyJdbc.url, MyJdbc.username, MyJdbc.password);
      MyJdbcTemplate.setConnection(connection);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void closeConnection() {
    try {
      if (MyJdbcTemplate.getConnection() != null && !MyJdbcTemplate.getConnection().isClosed()) {
        MyJdbcTemplate.getConnection().close();
        System.out.println("Connection连接关闭");
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
